package com.bw.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bw.common.ExcelUtils;
import com.bw.common.MonthUtils;
import com.bw.entity.SysOrder;
import com.bw.form.UserQueryForm;
import com.bw.service.SysOrderService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

@Controller
public class ExportController {

    /**
     * 服务对象
     */
    @Resource
    private SysOrderService sysOrderService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    //批量导出数据到excel
    @RequestMapping(value = "/getExcel")
    public void batchExport(HttpServletResponse response) {

        try {
            OutputStream outputStream = response.getOutputStream();
            //查询账单周期
            List<String> count = sysOrderService.getYM();
            //文件名
            String fileName = "租金账单导出.xlsx";
            //使用EasyExcel进行导出
            ExcelWriter excelWriter = EasyExcel.write(outputStream, SysOrder.class).build();
            ArrayList<Future> futureList = Lists.newArrayList();
            //不同的账单周期写入不同sheet页
            for (int i = 0; i < count.size(); i++) {
                String ym = count.get(i);
                //创建sheet页
                WriteSheet writeSheet = EasyExcel.writerSheet(i, ym).build();
                //异步分页查询  一页5000条数据 只查询 100页 （每个账单周期最多查询50w数据）
                Future<?> submit = threadPoolExecutor.submit(() -> {
                    //分页去数据库查询数据
                    Page page = new Page();
                    page.setSize(10);// 测试一页10条
                    UserQueryForm query = new UserQueryForm();
                    query.setStartDate(MonthUtils.getFirstDay(Integer.parseInt(ym.split("-")[0]), Integer.parseInt(ym.split("-")[1]), "yyyy-MM-dd"));
                    query.setEndDate(MonthUtils.getLastDay(Integer.parseInt(ym.split("-")[0]), Integer.parseInt(ym.split("-")[1]), "yyyy-MM-dd"));
                    List<SysOrder> objects = Lists.newArrayList();
                    for (int j = 1; j < 100; j++) {
                        page.setCurrent(j);
                        IPage<SysOrder> reportPage = sysOrderService.getReportPage(page, query);
                        List<SysOrder> records = reportPage.getRecords();
                        if (CollectionUtil.isEmpty(records)) {
                            break;
                        }
                        objects.addAll(records);
                    }
//                    excelWriter.write(objects, writeSheet);
                    if (CollectionUtil.isNotEmpty(objects)) {
                        synchronized (excelWriter) {
                            excelWriter.write(objects, writeSheet);
                        }
                    }

                });
                futureList.add(submit);
            }

            for (Future future : futureList) {
                future.get();
            }
            //下载
//            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");//以流的形式对文件进行下载
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));//对文件名编码,防止文件名乱码
            excelWriter.finish();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
